require 'yaml'

class Sound
  class << self
    attr_accessor :sounds
  
    def clear
      @sounds = {}
    end
    
    def load(filename)
      clear if @sounds.nil?
      path = File.dirname(filename)
      YAML::load_file(filename).each_pair do |id, options|
        id = id.to_sym
        options = options.inject({}) { |h, (k, v)| h[k.to_sym] = v; h }
        options[:sources] ||= ["#{id}.wav"]
        options[:sources].map! { |source| "#{path}/#{source}" }
        @sounds[id] = Sound.new id, options
      end
    end
  
    def play(id, options={})
      @sounds[id].play options
    end
    
    def playing(id)
      @sounds[id].playing? rescue nil
    end
  end
  
  def initialize(id, options={})
    @id = id
    @exclusive ||= options[:exclusive] || false
    @last_played ||= 0
    @length ||= options[:length] || 0
    @volume ||= options[:volume] || 1
    @sources ||= []
    options[:sources].each { |s| @sources << Gosu::Sample.new($window, s) }
  end
  
  def play(options={})
    return if (options[:exclusive] or @exclusive) and playing?
    @sources.random.play options[:volume] || @volume
    @last_played = now
  end
  
  def playing?
    !@length.milliseconds.since? @last_played
  end
end
